package com.dankegongyu.lib.http.request;

import android.text.TextUtils;

import java.util.Iterator;
import java.util.Map;

import okhttp3.OkHttpClient;

/**
 * @author wpq
 * @version 1.0
 */
@SuppressWarnings({"unchecked", "WeakerAccess"})
public abstract class BaseBodyRequest<T extends BaseBodyRequest> extends BaseRequest<T> {

    Object body;

    public BaseBodyRequest(String url, OkHttpClient okHttpClient) {
        super(url, okHttpClient);
    }

    /**
     * 建议body传Map或Serializable的实现类，避免字段被混淆导致服务端解析出错；
     * 如果有的POST或PUT等不需要Body，但是不传又报错，
     * 可以传个EmptyBody(class EmptyBody implements Serializable) 或 new HashMap<String, Object>()
     */
    public T body(Object body) {
        this.body = body;
        filterNullOrEmptyValue();
        return (T) this;
    }

    private void filterNullOrEmptyValue() {
        try {
            if (this.body instanceof Map) {
                Map<String, Object> map = (Map<String, Object>) this.body;
                // 删除value为空的元素
                Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry<String, Object> entry = it.next();
                    if (entry == null) {
                        it.remove();
                    } else {
                        Object value = entry.getValue();
                        if (value == null) {
                            it.remove();
                        } else if (value instanceof String) {
                            String valueStr = (String) value;
                            if (TextUtils.isEmpty(valueStr)) {
                                it.remove();
                            }
                        }
                    }
                }
            }
        } catch (Throwable e) {
//            e.printStackTrace();
        }
    }
}
